<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8"/>
<title>沙漠淘金</title>
<style>
  body{margin:0;background:#f7e9aa;font-family:Arial;text-align:center}
  #gameWrap{position:relative;width:320px;height:360px;margin:20px auto}
  #game{position:absolute;top:40px;left:0;width:320px;height:320px;border:2px solid #333}
  .cell{position:absolute;width:80px;height:80px;box-sizing:border-box;border:1px solid #ccc}
  .coin{background:gold;border-radius:50%;cursor:pointer}
  #score,#timer{position:absolute;top:10px;font-size:20px}
  #score{left:10px} #timer{right:10px}
  /* 遮罩样式 */
  #mask{
    position:fixed;inset:0;background:rgba(0,0,0,.75);
    display:flex;align-items:center;justify-content:center;
    color:#fff;font-size:24px;flex-direction:column;z-index:9999
  }
  #mask div{margin:6px 0}
</style>
</head>
<body>

<div id="gameWrap">
  <div id="score">金币：0</div>
  <div id="timer">60</div>
  <div id="game"></div>
</div>

<script>
/* ===================== 基础参数 ===================== */
const SIZE = 4, W = 80, TOTAL = 60;   // 4×4 格子，60 秒
let score = 0, timeLeft = TOTAL;
const params = new URLSearchParams(location.search);
const subj = params.get('subj') || 'test';
const cond = 'promo';

/* ===================== 创建格子 ===================== */
const game = document.getElementById('game');
for(let i=0;i<SIZE*SIZE;i++){
  const c = document.createElement('div');
  c.className='cell';
  c.style.left=(i%SIZE)*W+'px';
  c.style.top=Math.floor(i/SIZE)*W+'px';
  game.appendChild(c);
}
const cells = [...document.querySelectorAll('.cell')];

/* ===================== 随机放金币 ===================== */
function spawnCoin(){
  cells.forEach(c=>c.classList.remove('coin'));
  const idx = Math.floor(Math.random()*cells.length);
  cells[idx].classList.add('coin');
}
spawnCoin();

/* ===================== 点击检测 ===================== */
game.addEventListener('click',e=>{
  if(!e.target.classList.contains('coin')) return;
  score++;
  document.getElementById('score').textContent='金币：'+score;
  spawnCoin();
});

/* ===================== 倒计时 ===================== */
const timer = setInterval(()=>{
  timeLeft--;
  document.getElementById('timer').textContent=timeLeft;
  if(timeLeft<=0) finish();
},1000);

/* ===================== 游戏结束 ===================== */
function finish(){
  clearInterval(timer);
  game.style.pointerEvents='none';          // 禁止再点

  // 创建遮罩
  const mask = document.createElement('div');
  mask.id='mask';
  mask.innerHTML=`
      <div>时间到！</div>
      <div>您共收集了 ${score} 枚金币</div>
      <div style="font-size:16px">2 秒后自动返回问卷…</div>
  `;
  document.body.appendChild(mask);

  // 回传数据
  window.parent.postMessage({subj, cond, score}, '*');

  // 2 秒后告诉 Credamo 这一页结束
  setTimeout(()=>window.parent.postMessage({type:'pageFinish'},'*'), 2000);
}
</script>
</body>
</html>
